package dao.task;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

public class DbUtil_1 {      
    private static String driver;
    private static String url;
    private static String user;
    private static String password;

    static {
        Properties pro = new Properties();
        //获取src路径下的文件的方式--->ClassLoader类加载器
        ClassLoader classLoader = DbUtil_1.class.getClassLoader();
        InputStream resourceAsStream = classLoader.getResourceAsStream("db.properties");
        //2.加载文件
        try {
            pro.load(resourceAsStream);
            //3.获取数据，赋值
            driver = pro.getProperty("driver");
            url = pro.getProperty("url");
            user = pro.getProperty("username");
            password = pro.getProperty("password");
            //4.注册驱动
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public Connection getConnection() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return connection;
    }


    public void close(AutoCloseable object) {
        if (object != null) {
            try {
                object.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

   
    public int executeSql(String sql, Object... objs) {

        Connection con = this.getConnection();
        PreparedStatement stmt = null;
        try {
            stmt = con.prepareStatement(sql);
            for (int i = 0; i < objs.length; i++) {
                stmt.setObject(i + 1, objs[i]);
            }

          return stmt.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.close(stmt);
            this.close(con);
        }
        return 0;
    }


}
